package com.samtech.web.config;

import java.util.HashSet;

import javax.servlet.ServletContext;

//import org.apache.tiles.request.freemarker.servlet.SharedVariableLoaderFreemarkerServlet;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewResolverRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import org.springframework.web.util.WebUtils;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.spring4.SpringTemplateEngine;
import org.thymeleaf.spring4.view.ThymeleafViewResolver;
import org.thymeleaf.templatemode.TemplateMode;
import org.thymeleaf.templateresolver.ServletContextTemplateResolver;

import com.samtech.web.view.HtmlCacheViewResolver;

import nz.net.ultraq.thymeleaf.LayoutDialect;

@Configuration
@ComponentScan(basePackages= {"com.samtech.web.controller","com.samtech.web.admin.controller"},basePackageClasses= {MvcConfig.class})
public class MvcConfig extends WebMvcConfigurationSupport{
	final static int sixhours=6*60*60;
	
	@Override
	protected void addResourceHandlers(ResourceHandlerRegistry registry) {
		super.addResourceHandlers(registry);
		registry.addResourceHandler("/static/**").addResourceLocations("/static/");
		registry.addResourceHandler("/js/**");
		registry.addResourceHandler("/*.ico");
		registry.addResourceHandler("/**/**.js").setCachePeriod(sixhours/3);
		registry.addResourceHandler("/**/**.css").setCachePeriod(sixhours);
		registry.addResourceHandler("/img/**.*").setCachePeriod(sixhours*2);
		registry.addResourceHandler("/wjs/**").addResourceLocations("classpath:/META-INF/resources/webjars/").setCachePeriod(sixhours*8);
		//registry.addResourceHandler("**.html").resourceChain(true);//.addResolver(bldViewResolver());
	}
	
	
	@Bean
	HtmlCacheViewResolver bldViewResolver() {
		HtmlCacheViewResolver resolver=new HtmlCacheViewResolver();
		return resolver;
	}
	/*@Bean
    public TilesViewResolver tilesViewResolver() {
        TilesViewResolver viewResolver = new TilesViewResolver();
        viewResolver.setViewClass(TilesView.class);
        viewResolver.setOrder(3);
        return viewResolver;
    }*/

	/*@Bean
    public ServletRegistrationBean freemarkerServlet() {
        SharedVariableLoaderFreemarkerServlet servlet = new SharedVariableLoaderFreemarkerServlet();
        StandardWrapper wrapper = new StandardWrapper();
        wrapper.addInitParameter("org.apache.tiles.request.freemarker.CUSTOM_SHARED_VARIABLE_FACTORIES",
                "tiles,org.apache.tiles.freemarker.TilesSharedVariableFactory");
        try {
            servlet.init(new StandardWrapperFacade(wrapper));
        } catch (ServletException e) {
            log.error("freemarker初始化失败", e.getMessage());
        }
        return new ServletRegistrationBean(servlet, "*.ftl");
    }*/
	
	private TemplateEngine bldTemplateEngine(final ServletContext servletContext) {
		TemplateEngine engine = new SpringTemplateEngine();// TemplateEngine();
		//html template
		ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver(servletContext);
		templateResolver.setTemplateMode(TemplateMode.HTML);
		templateResolver.setPrefix("/WEB-INF/templates/thymeleaf/");
		templateResolver.setSuffix(".html");
		templateResolver.setCharacterEncoding("utf-8");
		//templateResolver.set
		HashSet<String> sets = new HashSet<String>(2);
		sets.add( "*_th");
		templateResolver.setResolvablePatterns(sets);
		Long cacheTTLMs=36_000_000l;
		templateResolver.setCacheTTLMs(cacheTTLMs);
		templateResolver.setCacheable(false);//true
		engine.addTemplateResolver(templateResolver);
		//javascript template
		templateResolver = new ServletContextTemplateResolver(servletContext);
		templateResolver.setTemplateMode(TemplateMode.JAVASCRIPT);
		templateResolver.setPrefix("/WEB-INF/templates/thymeleaf/");
		HashSet<String> sets2 = new HashSet<String>(2);
		sets2.add( "*_jth");
		templateResolver.setResolvablePatterns(sets2);
		templateResolver.setSuffix(".js");
		templateResolver.setCharacterEncoding("utf-8");
		engine.addTemplateResolver(templateResolver);
		engine.addDialect(new LayoutDialect());
		
		return engine;
	}
	
	@Bean
	public ThymeleafViewResolver bldThymeViewResolver(){
		ThymeleafViewResolver resolver = new ThymeleafViewResolver();
		resolver.setCache(false);//true
		//resolver.setCacheLimit(100);
		resolver.setCharacterEncoding("utf-8");
		resolver.setTemplateEngine(bldTemplateEngine(getServletContext()));
		resolver.setViewNames(new String[]{"*_th","*_jth"});
		resolver.setOrder(Integer.MAX_VALUE-10);
		return resolver;
	}
	
	@Override
	public void setServletContext(ServletContext servletContext) {
				super.setServletContext(servletContext);
				WebUtils.setWebAppRootSystemProperty(getServletContext());
	}
	
	@Override
	protected void configureViewResolvers(ViewResolverRegistry registry) {
		registry.viewResolver(bldThymeViewResolver());
		registry.viewResolver(bldViewResolver());
	}
}
